const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        discount_price:0,
        totals_prices:0,
        minimumamount:0,
        total_price:0,
        durationfee:0,
        prezzo:0,
        pledge_price:0,
        totals:0,
        price:20,
        TotalPrice:0,
        deposit:0,
        order_id: 0,
        order: {},
        user: {},
        pay_type: 2,    //支付类型 1余额 2微信
        coupon_id: 0,   //优惠卷id
        coupon_sub: 0,  // 优惠卷金额
        vip_sub: 0,     //会员折扣
        pay_price: 0,   //支付金额
        rate: 0,    //折扣比例
        store_label:[],
        windowHeight: 654,
        
        clock_time:0,//时间戳
        maxtime: "",
        isHiddenLoading: true,
        isHiddenToast: true,
        dataList: {},
        countDownDay: 0,
        countDownHour: 0,
        countDownMinute: 0,
        countDownSecond: 0,
        //定时器
        payinterval:'',
        fw_status:true,
        countDowns: {
            minutes: '30',
            seconds: '00'
          },
          countdownValue:0,
        //  30分钟倒计时
        countdownTime: 30 * 60, // 倒计时剩余时间，单位：秒30 * 60,
        // countdownText: '30:00', // 格式化后的倒计时文本30:00
        // countdown:''
    },
    pay_success: function () {
        this.payOrder(this.data.pay_type,1);
    },
    account_chongzhi: function () {
        wx.navigateTo({
            url: '/pages/account_chongzhi/account_chongzhi',
        })
    },
    setPayType: function (e) {
        var type = e.currentTarget.dataset.type;
        this.setData({
            pay_type: type
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
    },
      /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      wx.removeStorageSync('paymentStatus');
      wx.removeStorageSync('start');
           // 全局倒计时
           setTimeout(()=>{
            const app = getApp();
            app.getHaerl(); // 调用 app.js 中的 getHaerl 方法
            setInterval(() => {
              this.setData({ countdownValue: app.globalData.formattedCountdown });
              
            }, 1000);

           },800)
    },

     
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var order_id = options.order_id || 0;
           wx.setStorageSync('order_id', order_id),
            user = wx.getStorageSync('user');
            this.data.deposit= wx.getStorageSync('deposit');
        this.setData({
            order_id: order_id,
            user: user,
            TotalPrice:   options.TotalPrice || 0,
            deposit:this.data.deposit || 0,
            
        });
        this.getOrder();
              // 全局倒计时
              const app = getApp();
              setInterval(() => {
                this.setData({ countdownValue: app.globalData.formattedCountdown });
              }, 1000);
              app.getHaerl(); // 调用 app.js 中的 getHaerl 方法
              
    },
        /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.countdownInterval);
    },
    // 下面
      formatTime: function(val) {
        return val < 10 ? '0' + val : val;
      },
    //   倒计时30分钟
    cancelOrder: function() {
        app.ajax({
            url: '/api/order/cancell',
            data: {
                order_id:this.data.order_id // 这里替换成你的订单号
            },
            success: function(res) {
              // 取消订单成功的处理逻辑
              wx.showToast({
                title: res.msg,
                icon: 'none',
                success: function() {
                  wx.reLaunch({
                    url: '/pages/my_order/my_order'
                  });
                }
              });
            },
            fail: function(err) {
              // 取消订单失败的处理逻辑
            }
          });
      },
    goCupon:function(){
        wx.navigateTo({
            url: '/pages/coupon/coupon',
        })
    },
    getOrder: function () {
        console.log(this.data.order_id,'this.data.order_id------')
        app.ajax({
            url: '/api/order/payOrder',
            data: {
                order_id: this.data.order_id,
             
            },
            success: res => {
             let durationfee=res.data.use_hours*res.data.price
                this.setData({
                    datetime:res.datetime,
                    pledge_price:res.data.pledge_price,
                    use_hours:res.data.use_hours,
                    totals:res.data.use_hours*res.data.price+ Number(res.data.pledge_price),   
                    status:res.data.status,
                    durationfee:durationfee.toFixed(2),
                    total_price:res.data.total_price,
                    totals_prices:res.data.use_hours*Number(res.data.price),
                    discount_price:res.data.discount_price
                    // total_price:res.data.use_hours*Number(res.data.pledge_price)
                })
                wx.setStorageSync('status',res.data.status)
           
                this.datahader(res.data.create_time)
                if (res.code == 1) {
                    this.setData({
                        price:res.data.price
                    })
                    var coupon_id = 0,
                        coupon_sub = 0,
                        vip_sub = 0,
                        pay_price = 0,
                        total_price = parseFloat(res.data.total_price);
                    if (res.data.coupons.length > 0) {
                        coupon_sub = parseFloat(res.data.coupons[0].money);
                        coupon_id = res.data.coupons[0].id;
                    }
                    pay_price = total_price - coupon_sub;
                    var rate = parseFloat(res.data.discount_rate);//discount_rate: 1
                    this.data.coupon_id = coupon_id;
                    this.data.coupon_sub = coupon_sub;
                    this.data.rate = rate;
                    if (rate > 0) {
                        vip_sub = pay_price * (10 - rate) / 10;
                        vip_sub = vip_sub.toFixed(2);
                        vip_sub = parseFloat(vip_sub);
                    }
                    pay_price = pay_price - vip_sub;
                    this.setData({
                        order: res.data,
                        coupon_id: coupon_id,
                        coupon_sub: coupon_sub,
                        vip_sub: vip_sub,
                        pay_price: pay_price,
                        store_label:res.data.label,
                        clock_time:res.data.start, 
                        
                    })
                    if(res.data.coupons.length){
                        this.setData({
                            minimumamount:res.data.coupons[0].min||0
                        })
                    }
                    let that =this
                    //      let pas=this.data.totals-this.data.vip_sub
                    //            
                    // let pas=this.data.total_price-this.data.vip_sub-this.data.minimumamount
                    // discount_price
                    let pas=this.data.total_price-this.data.vip_sub-this.data.discount_price
                    // debugger
                    console.log(pas,'pas---------')    
                                    this.setData({
                                        prezzo:pas.toFixed(2)
                                    })

                    setTimeout(()=>{
                    //   that.countDown();
                  },1000)
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            }
        }, 1);

        
    },
    // 转换为日期
    datahader:function(e){
    // 将时间戳转换为日期对象
    const timestamp = e; // 注意要将秒数转换为毫秒数
    const date = new Date(timestamp);
    // 获取日期的年、月、日
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从0开始，需要加1
    const day = date.getDate();
    // 获取日期的小时、分钟、秒
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    // 构建日期字符串
    const dateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    this.data.end=dateString
    console.log(dateString,  this.data.end,e,'2022-08-01 13:07:33'); // 输出：2022-08-01 13:07:33
  this.setData({
      end:this.data.end
  })
    },
    //启动定时获取支付信息
    payTiming:function(){
        this.payOrder(1,2);
        this.payinterval = setInterval(function () {
            this.payOrder(1,2);
        }.bind(this), 5000);
   },
   /**                              // operation_type ==2时  pay_type值无效
    * @param {*} pay_type           //支付方式 1余额 2微信
    * @param {*} operation_type     //1支付 2获取账单
    */
   payOrder:function(pay_type,operation_type){
       let _this=this
       console.log( this.data.order_id,this.data.coupon_id,pay_type,operation_type,'pay_type,operation_type---------')
        app.ajax({
            url: '/api/order/pay',
            data: {
                // // 上面
                // order_id: this.data.order_id,//订单id
                // // coupon_id: this.data.coupon_id,//
                // pay_type: pay_type,//支付类型
                // operation_type:operation_type,//会员扣掉的金额
                // 下面
                    order_id: this.data.order_id,//订单id
                    pay_type: pay_type,//支付类型
                   sub_price:this.data.vip_sub//会员扣掉的金额

            },
            success: res => {
                if (res.code == 1) {
                    if(res.data &&_this.data.pay_type == 1){
                        wx.removeStorageSync('order_id')
                        wx.removeStorageSync('status')
                        wx.removeStorageSync('couponid')
                        wx.removeStorageSync('allcouponid')
                        
                        let _res=res
                        // app.globalData.countdown=0
                        wx.showModal({
                            title: '提示',
                            content: '确定要余额支付'+this.data.prezzo+'元吗？',
                            success: function (res) {
                              if (res.confirm) {
                                console.log('余额支付支付成功')
                                wx.showToast({
                                    title: _res.msg,
                                    icon: 'none'
                                }) 
                                setTimeout(()=>{
                                    wx.redirectTo({
                                        url: '/pages/my_order/my_order'
                                    })
                                },1000)
                                console.log('用户点击确定');
                                // 在这里执行删除操作
                              } else if (res.cancel) {
                                console.log('用户点击取消');
                              }
                            }
                          })

                        // 
                            // console.log('余额支付支付成功')
                            // wx.showToast({
                            //     title: res.msg,
                            //     icon: 'none'
                            // }) 
                            // setTimeout(()=>{
                            //     wx.redirectTo({
                            //         url: '/pages/my_order/my_order'
                            //     })
                            // },1000)
                         

                    }else{
                        clearInterval(this.payinterval);
                        if (res.data &&_this.data.pay_type == 2) {
                           console.log(res,'这是订单计算的页面','')
                            wx.requestPayment({
                                nonceStr: res.data.nonceStr,
                                package: res.data.package,
                                paySign: res.data.paySign,
                                timeStamp: res.data.timeStamp,
                                signType: res.data.signType,
                                success: res => {
                                
                        wx.removeStorageSync('order_id')
                        wx.removeStorageSync('status')
                        wx.removeStorageSync('couponid')
                        wx.removeStorageSync('allcouponid')
                        app.globalData.countdown=0
                                    console.log(app.globalData.countdown,'微信支付成功')
                                    wx.navigateTo({
                                        url: '/pages/my_order/my_order'
                                    })
                                }
                            })
                        } else {
                            wx.redirectTo({
                                url: '/pages/my_order/my_order'
                            })
                        }
                    }
                } else {
                    //订单已经结束返回首页
                  if(res.data == 100){
                    wx.reLaunch({
                      url: '/pages/index/index'
                  })
                  clearInterval(this.payinterval);
                  }
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            }
        }, 1);
   },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
       
    },
    

 

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
      wx.showLoading({
        title: '加载中...'
      });
      // 模拟异步请求最新数据
      setTimeout(() => {
        // 在这里执行获取最新数据的逻辑，比如调用接口获取数据
        this.getOrder()
        // 数据获取完成后隐藏加载提示
        wx.hideLoading();
        // 停止当前页面下拉刷新
        wx.stopPullDownRefresh();
      }, 1000)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    date:function(timestamp) {
	    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	    var Y = date.getFullYear() + '-';
	    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        if(date.getDate() < 10){
            var D = '0' + date.getDate() + ' ';
        }else{
            var D = date.getDate() + ' ';
        }
	    var h = date.getHours() + ':';
        var m = date.getMinutes();
        // var m = date.getMinutes() + ':';
	    // var s = date.getSeconds();
	    return Y + M + D + h + m;
    },
    cancellation(e){
        let _this=this
          // 全局倒计时
          const app = getApp();
        //   setInterval(() => {
        //     this.setData({ countdownValue: app.globalData.formattedCountdown });
        //   }, 1000);
        //   app.getHaerl(); // 调用 app.js 中的 getHaerl 方法
        // 下面
        var room_id = e.currentTarget.dataset.room_id;
        wx.showModal({
            title: '取消订单',
            content: '确认取消订单吗？',
            success (res) {
              if (res.confirm) {
                app.ajax({
                    //   url: '/api/user/checkOutRoom',
                        url:'/api/order/cancell',
                      data: {
                        order_id: room_id
                      },
                      success: res => {
                        if(res.code == 1){
                            wx.showToast({
                                title: res.msg,
                                icon: 'none',
                                success: function() {
                                  wx.removeStorageSync('order_id')
                                  wx.removeStorageSync('status')
                                  wx.removeStorageSync('couponid')
                                  wx.removeStorageSync('allcouponid')
                                  app.globalData.formattedCountdown='00:00'
                                  _this.setData({
                              countdownValue: app.globalData.formattedCountdown='00:00'
                                  })
                                  setTimeout(()=>{
                                    wx.reLaunch({
                                      url: '/pages/my_order/my_order'
                                    });
                                  },1000)
                                 
                                }
                              });
                        }
                      }
                    }, 1);
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
    },
    pay_successs(){
this.payOrders(1,1)

    },

// 支付

payOrders:function(pay_type,operation_type){
   
     app.ajax({
         url: '/api/user/pay',
         data: {
             // 上面
             order_id: this.data.order_id,//订单id
             pay_type: pay_type,//支付类型
             operation_type:operation_type,//会员扣掉的金额
         },
         success: res => {
             if (res.code == 1) {
                 if(operation_type == 2){
                     var bill_money = res.data.bill_list[0].money; 
                     var pay_price = bill_money - this.data.coupon_sub;
                     var vip_sub = 0;
                     if (this.data.rate > 0) {
                         vip_sub = pay_price * (10 - this.data.rate) / 10;                           
                         vip_sub = vip_sub.toFixed(2);
                         vip_sub = parseFloat(vip_sub);
                     }
                     pay_price = pay_price - vip_sub;
                     var coupon_info = this.data.coupon_sub + vip_sub;
                     this.setData({
                         order_create_time:this.date(this.data.order.create_time),
                         bill_create_time: res.data.bill_data.create_time,
                         bill_hours: res.data.bill_data.hours,
                         bill_money:this.data.TotalPrice,
                         pay_price:this.data.TotalPrice,
                         coupon_info:coupon_info,
                     
                     });
                 }else{
                     clearInterval(this.payinterval);
                     if (res.data && pay_type == 2) {
                         wx.requestPayment({
                             nonceStr: res.data.nonceStr,
                             package: res.data.package,
                             paySign: res.data.paySign,
                             timeStamp: res.data.timeStamp,
                             signType: res.data.signType,
                             success: res => {
                                 console.log(res);
                                 wx.navigateTo({
                                   
                                     url: '/pages/my_order/my_order'
                                 })
                             }
                         })
                     } else {
                        
                         wx.redirectTo({
                             url: '/pages/my_order/my_order'
                         })
                     }
                 }
             } else {
                 //订单已经结束返回首页
               if(res.data == 100){
                 wx.reLaunch({
                   url: '/pages/index/index'
               })
               clearInterval(this.payinterval);
               }
                 wx.showToast({
                     title: res.msg,
                     icon: 'none'
                 })
                 //console.log(res.msg);
             }
         }
     }, 1);
},

})

